package com.koron.css2.newProjectCenter.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.BusinessAreaMapper;
import com.koron.css2.baseConfig.mapper.ConfigMapper;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.newProjectCenter.Enum.PjInfoProcessStateEnum;
import com.koron.css2.newProjectCenter.bean.PjPendingBean;
import com.koron.css2.newProjectCenter.bean.PubUpTimeInstance;
import com.koron.css2.newProjectCenter.bean.query.PjInfoQueryBean;
import com.koron.css2.newProjectCenter.bean.query.PubUpTimeInstanceQuery;
import com.koron.css2.newProjectCenter.impl.pubUpTime.WorkDayUtils;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.newProjectCenter.mapper.PubUpTimeInstanceMapper;
import com.koron.css2.newProjectCenter.mapper.WorkDayMapper;
import com.koron.css2.newProjectCenter.vo.PjInfoListVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.systemManage.mapper.OrgUserMapper;
import com.koron.util.Constant;
import com.koron.util.DateUtils;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 审批列表查询
 */
public class PjInfoList implements ServerInterface {

    @Override
    @SuppressWarnings("rawtypes")
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            PjInfoMapper mapper = factory.getMapper(PjInfoMapper.class);
            OrgUserMapper orgUserMapper = factory.getMapper(OrgUserMapper.class, "_default");

            PjInfoQueryBean queryBean = JsonUtils.objectToPojo(req.getData(), PjInfoQueryBean.class);
            Map<String, String> PIS = Tools.mapDicByCode(factory, "PIS");
            Map<String, String> PPT = Tools.mapDicByCode(factory, "PPT");

            BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);

            // 1. 报装日期不能为空
            if (StringUtils.isBlank(queryBean.getBeginDate()) || StringUtils.isBlank(queryBean.getEndDate())) {
                return MessageBean.create(Constant.NOT_NULL, "报装日期不能为空", null);
            }
            // 1.1 优化查询当天数据
            DateUtils.formatDateToDateTime(queryBean.getBeginDate(), queryBean.getEndDate());
            // 2. 优化查询，非必要，不联表
            List<String> fuzzyItems = queryBean.getFuzzyItems();
            int userCtmTempFlag = 0;
            if (fuzzyItems != null && (fuzzyItems.contains("b.ctm_name") || fuzzyItems.contains("b.cert_no") || fuzzyItems.contains("b.mobile"))) {
                userCtmTempFlag = 1;
                queryBean.setUserCtmTempFlag(userCtmTempFlag);
            }
            if (Objects.equals("C021905", userInfo.getCurWaterCode())) {
                List<String> businessAreaList = orgUserMapper.selectSysUserArea(userInfo.getUserInfo().getAcount());
                if (businessAreaList.size() > 0) {
                    queryBean.setBusinessAreaList(businessAreaList);
                }
            }
            // 系统参数-政府检查(PROJECT_ZFCHECK_STATUS-0.否，1.是)为是，同时对接工建参数为是时，则排除“上传”为否的记录
            ConfigMapper configMapper = factory.getMapper(ConfigMapper.class);
            String configvalue = configMapper.getConfigValueByNameOn("PROJECT_ZFCHECK_STATUS");
            String isAbutmentBuild = configMapper.getConfigValueByNameOn("PROJECT_GJDJ_STATUS");
            queryBean.setIsGovernmentCheck(configvalue);
            queryBean.setIsAbutmentBuild(isAbutmentBuild);
            // 3. 设置分页参数
            PageHelper.startPage(queryBean.getPage(), queryBean.getPageCount());
            // 4. 查询列表
            List<PjInfoListVO> list = mapper.selectList(queryBean);
            // 5. 查询对应的客户信息并转map
            Map<String, CtmInfoBean> ctmMap = null;
            if (list != null && !list.isEmpty() && userCtmTempFlag == 0) {
                List<String> userCtmTempIdList = list.stream().map(PjInfoListVO::getUserCtmTempId).collect(Collectors.toList());
                CtmInfoMapper ctmInfoMapper = factory.getMapper(CtmInfoMapper.class);
                List<CtmInfoBean> ctmInfoBeanList = ctmInfoMapper.getListByIdList(userCtmTempIdList, CtmInfoBean.CTMTEMP);
                ctmMap = ctmInfoBeanList.stream().collect(Collectors.toMap(CtmInfoBean::getId, Function.identity()));
            }
            // PjProcessNodeTimePostponeMapper postponeMapper = factory.getMapper(PjProcessNodeTimePostponeMapper.class);
            WorkDayMapper workDayMapper = factory.getMapper(WorkDayMapper.class);
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (PjInfoListVO bean : list) {
                PubUpTimeInstanceMapper pubUpTimeInstanceMapper = factory.getMapper(PubUpTimeInstanceMapper.class);
                PubUpTimeInstanceQuery queryBeans = new PubUpTimeInstanceQuery();
                queryBeans.setFlowId(bean.getId());
                queryBeans.setNode(bean.getProcessState());
                LocalDateTime startTime = LocalDateTime.parse(bean.getCreateTime(), dtf);
                long start2Now = WorkDayUtils.workMinutes(startTime, LocalDateTime.now(), workDayMapper);
                if (start2Now > 60)
                    bean.setUsedTime(start2Now / 60 + "小时" + (start2Now % 60) + "分钟");
                else if (start2Now > 0)
                    bean.setUsedTime(start2Now + "分钟");
                // 获取计划时间总和，单位：小时
                Integer planSum = workDayMapper.getPlanSum();
                if (planSum != null && planSum > 0) {
                    bean.setPlanSum(planSum);
                    String planEndTime = WorkDayUtils.calcEndTime(workDayMapper, startTime, planSum);
                    if (!StringUtils.isBlank(planEndTime)) {
                        bean.setPlanTime(WorkDayUtils.convertStringToDate(planEndTime));
                        long minutes = WorkDayUtils.minutesBetweenNow(bean.getPlanTime());
                        if (minutes > 60) {
                            bean.setProjectTimeOut("超期");
                        } else if (minutes > 0) {
                            bean.setProjectTimeOut("警告");
                        } else {
                            bean.setProjectTimeOut("未超期");
                        }
                    }
                }
                List<PubUpTimeInstance> PubUpTimeInstancelist = pubUpTimeInstanceMapper.selecList(queryBeans);
                if (PubUpTimeInstancelist != null && !PubUpTimeInstancelist.isEmpty()) {
                    PubUpTimeInstance pubUpTimeInstance = PubUpTimeInstancelist.get(0);

                    LocalDateTime endTime = LocalDateTime.parse(pubUpTimeInstance.getEndTime(), dtf);
                    long now2End = WorkDayUtils.workMinutes(LocalDateTime.now(), endTime, workDayMapper);
                    if (now2End > 60) {
                        bean.setCurrentNodetimeOutFlag("未超期");
                    } else if (now2End > 0) {
                        bean.setCurrentNodetimeOutFlag("警告");
                    } else {
                        bean.setCurrentNodetimeOutFlag("超期");
                    }
                }

                /*if (ObjectUtil.isNotNull(bean.getPlanSum())&&ObjectUtil.isNotNull(bean.getUsedSum())){
                    Integer planSum = bean.getPlanSum();
                    Integer usedSum = bean.getUsedSum();
                    Integer outTime=usedSum-planSum;
                    bean.setProjectTimeOut(outTime>0?outTime+"时":"未超期");
                }else {
                    bean.setProjectTimeOut("未超期");
                }*/
                Integer workDays = bean.getWorkDays();
                Integer workHours = bean.getWorkHours();
                StringBuilder builder = new StringBuilder();
                if (ObjectUtil.isNotNull(workDays) && workDays > 0) {
                    builder.append(workDays).append("天");
                }
                if (ObjectUtil.isNotNull(workHours)) {
                    builder.append(workHours).append("时");
                }

                // bean.setUsedTime(builder.toString());
                String processState = bean.getProcessState();
                if (StringUtils.isBlank(processState)) {
                    processState = PjInfoProcessStateEnum.REGISTER.getProcessState();
                }
                // PjProcessNodeTimePostponeBean postponeBean = postponeMapper.getOneByPjIdAndProcessState(bean.getId(), processState);
                // if (ObjectUtil.isNotNull(postponeBean)) {
                //     Integer planTime = postponeBean.getPlanTime() == null ? 0 : postponeBean.getPlanTime();
                //     Integer timeConsum = postponeBean.getTimeConsum() == null ? 0 : postponeBean.getTimeConsum();
                //     Integer outTime = timeConsum - planTime;
                //
                //     bean.setCurrentNodetimeOutFlag(0 == postponeBean.getTimeOutFlag() ? "未超期" : outTime + "时");
                // } else {
                //     bean.setCurrentNodetimeOutFlag("未超期");
                // }
                // 6.2 转换数据字典
                bean.setSourceFlag(PIS.get(bean.getSourceFlag()));
                bean.setPjType(PPT.get(bean.getPjType()));
                // 转换状态
                bean.setProcessState(Tools.transProcessStatus(bean.getProcessState()));
                // 假如工程单属于已挂起，则设置流程状态未已挂起
                if (bean.getPendingState() == PjPendingBean.PENDED_STATE) {
                    bean.setProcessState("已挂起");
                }
                // // 超期状态
                // if (ObjectUtil.isNotNull(bean.getTimeOutFlag()) && bean.getTimeOutFlag() == 1) {
                //     bean.setTimeOutFlagName("已超期");
                //     bean.setProjectTimeOut("已超期");
                // } else {
                //     bean.setTimeOutFlagName("未超期");
                //     bean.setProjectTimeOut("未超期");
                // }
                if (userCtmTempFlag == 0 && ctmMap != null && !ctmMap.isEmpty()) {
                    // 20220704: 兼容数据为空的情况
                    CtmInfoBean ctmInfoBean = ctmMap.get(bean.getUserCtmTempId());
                    if (ctmInfoBean != null) {
                        bean.setCtmName(ctmMap.get(bean.getUserCtmTempId()).getCtmName());
                        bean.setCertNo(ctmMap.get(bean.getUserCtmTempId()).getCertNo());
                        bean.setMobile(ctmMap.get(bean.getUserCtmTempId()).getMobile());
                    }
                }
                if (bean.getDelayState() == 1) {
                    bean.setDelayStateName("已延期");
                } else {
                    bean.setDelayStateName("未延期");
                }
                // 转换驳回状态
                if (bean.getOverruleFlag() != null && bean.getOverruleFlag() == 1) {
                    bean.setOverruleFlagName("驳回");
                }
                if (bean.getPrepayType() != null && "1".equals(bean.getPrepayType())) {
                    bean.setPrepayType("预代决");
                }
                if (bean.getPrepayType() != null && "2".equals(bean.getPrepayType())) {
                    bean.setPrepayType("预决算");
                }
                if (bean.getBearCost() != null && "1".equals(bean.getBearCost())) {
                    bean.setBearCost("工程费");
                }
                if (bean.getBearCost() != null && "2".equals(bean.getBearCost())) {
                    bean.setBearCost("设计费");
                }
                if (bean.getNoBearCost() != null && "1".equals(bean.getNoBearCost())) {
                    bean.setNoBearCost("工程费（水表费）");
                }
                if (bean.getNoBearCost() != null && "2".equals(bean.getNoBearCost())) {
                    bean.setNoBearCost("设计费");
                }

                if (bean.getOverruleFlag() != null && bean.getOverruleFlag() == 2) {
                    bean.setOverruleFlagName("二次提交");
                }
                // 已废弃 -> 已终止
                if (StringUtils.isNotEmpty(processState) && processState.equals("已废弃")) {
                    bean.setProcessState("已终止");
                }
                String processName = bean.getProcessName();
                if (StringUtils.isNotEmpty(processName) && processName.equals("已废弃")) {
                    bean.setProcessName("已终止");
                }
                // 缴清标志
                Integer payOffFlag = bean.getPayOffFlag();
                if (payOffFlag != null && payOffFlag == 0) {
                    bean.setPayOffFlagName("未缴清");
                }
                if (payOffFlag != null && payOffFlag == 1) {
                    bean.setPayOffFlagName("已缴清");
                }
                // 签合同标志
                Integer signContractFlag = bean.getSignContractFlag();
                if (signContractFlag != null && signContractFlag == 0) {
                    bean.setSignContractFlagName("未签");
                }
                if (signContractFlag != null && signContractFlag == 1) {
                    bean.setSignContractFlagName("已签");
                }
                // 营业区域转换
                if (StringUtils.isNotBlank(bean.getBusinessArea())) {
                    bean.setBusinessArea(
                            businessAreaMapper.findBusinessAreaById(bean.getBusinessArea(), userInfo.getCurWaterCode()));
                }
            }
            MessageBean<PageInfo> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", PageInfo.class);
            info.setData(new PageInfo<>(list));
            return info;
        } catch (Exception e) {
            factory.close(false);
            logger.error("用水咨询列表查询失败" + e.getMessage(), e);
            e.printStackTrace();
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", null);
        }
    }
}
